package com.iking.housekeeping.service.export;

import com.github.pagehelper.Page;
import com.iking.housekeeping.dao.servicerecord.ServiceRecordMapper;
import com.iking.housekeeping.entity.dept.SysDept;
import com.iking.housekeeping.entity.export.ExportModel;
import com.iking.housekeeping.entity.servicerecord.ServiceRecord;
import com.iking.housekeeping.entity.servicestaff.ServiceStaff;
import com.iking.housekeeping.httpbean.servicerecord.HttpServiceRecord;
import com.iking.housekeeping.httpbean.servicerecord.SelectServiceRecord;
import com.iking.housekeeping.httpbean.servicestaff.reqbean.SelectServiceRes;
import com.iking.housekeeping.httpbean.servicestaff.reqbean.StaffBySelect;
import com.iking.housekeeping.service.dept.DeptService;
import com.iking.housekeeping.service.dtuser.DeptUserService;
import com.iking.housekeeping.service.servicestaff.ServiceStaffService;
import com.iking.housekeeping.util.PoiExcelExport;
import com.iking.housekeeping.util.UUIDUtil;
import com.iking.housekeeping.util.token.WebTokenUtil;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author root
 * @Date 2018/5/18
 * @Describe
 */
@Service
public class ExportService {

    @Autowired
    private DeptService deptService;
    @Autowired
    private ServiceRecordMapper serviceRecordMapper;
    @Autowired
    private ServiceStaffService serviceStaffService;
    /**
     * 导出服务记录
     */
    public String exportRecorder(SelectServiceRecord selectServiceRecord, HttpServletRequest request){
        int month =0;
        int index =1;
        List<ExportModel> exportModels = new ArrayList<>();
         if(selectServiceRecord.getfQuantumTimeBegin() !=null && !"".equals(selectServiceRecord.getfQuantumTimeBegin())){
             SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
             String begin=format.format(selectServiceRecord.getfQuantumTimeBegin());
             String end=format.format(selectServiceRecord.getfQuantumTimeEnd());
             index=Integer.parseInt(begin.substring(5,7));
             month=Integer.parseInt(end.substring(5,7));
         }else{
             Calendar calendar=Calendar.getInstance();
           //获得当前时间的月份，月份从0开始所以结果要加1
             month=calendar.get(Calendar.MONTH)+1;
         }
        //获取当前登录人id
        String userId = WebTokenUtil.getUserIdByRequest(request);
        List<SysDept> menuList = deptService.selectAdminById(userId);
        List<SysDept> list = deptService.selectAdminById(userId);
        //判断当前登录人是否为区域管理员
        if ("".equals(menuList.get(0).getfDeptPCode()) || menuList.get(0).getfDeptPCode() == null) {
            //查看所有区域数据
            selectServiceRecord.setfStreetCommunity(menuList.get(0).getfId());
        } else {
            if(list.contains(menuList.get(0).getfDeptPCode()) || menuList.get(0).getfAdminUser()!=""){
                //查看二级服务数据
                selectServiceRecord.setfStreetCommunity(menuList.get(0).getfId());
            }else{
                //查看自己服务数据
                selectServiceRecord.setfStreetCommunity(menuList.get(0).getfId());
            }
        }
        for(int i=index; i<= month; i++ ){
            selectServiceRecord.setfMonth(Integer.toString(i));
          //其中获取的街道社区为一个字段用，分开表示
           List<Map<String, Object>> results = serviceRecordMapper.selectByPage_hash(selectServiceRecord);
           for (Map<String, Object> dt:results) {
             Object ob =dt.get("fStreetCommunity");
             if(ob==null){
                continue;
             }
            String fStreetCommunity[] =ob.toString().split(",");
               dt.put("fStreet",fStreetCommunity[0]);
               if(fStreetCommunity.length==2){
                   dt.put("fStreet",fStreetCommunity[1]);
               }
               else  if(fStreetCommunity.length==3){
                   dt.put("fStreet",fStreetCommunity[1]);
                   dt.put("fCommunity",fStreetCommunity[2]);
               }
        }
        String columnName[] = { "编号", "姓名", "年龄", "性别", "电话", "地址", "街道办", "社区", "日期", "项目", "服务人","备注" };
        String propertyName[] = { "rownum", "fName", "fAge", "fGender", "fPhone", "fAddress", "fStreet", "fCommunity", "fBegintime", "fServiceType", "fServiceStaff", "fRemarks" };
        ExportModel exportModel = new ExportModel();
        exportModel.setSheetName(i+"月份");
        exportModel.setTitleName("hello");
        exportModel.setColumnName(columnName);
        exportModel.setPropertyName(propertyName);
        exportModel.setDataList(results);
        exportModels.add(exportModel);
        }
        //生成Excel
        String path = this.filePath(request);
        path +=UUID.randomUUID()+"派单备查表.xls";
        PoiExcelExport excel = new PoiExcelExport(path);
        excel.wirteExcel(exportModels);
        return path;
    }

    /**
     * 导出服务人员服务老人表
     */
    public String exportServiceElderly(StaffBySelect selectServiceRecord, HttpServletRequest request){
     Page<SelectServiceRes> list  =serviceStaffService.selectAll(selectServiceRecord,request);
        List<ExportModel> exportModels = new ArrayList<>();
       for(int i=0; i< list.size(); i++ ){
           SelectServiceRecord record =new SelectServiceRecord();
           record.setfServiceStaffID(list.get(i).getfId());
            //其中获取的街道社区为一个字段用，分开表示
            List<Map<String, Object>> results = serviceRecordMapper.selectByPage_hash(record);
            for (Map<String, Object> dt:results) {
                Object ob =dt.get("fStreetCommunity");
                if(ob==null){
                    continue;
                }
                String fStreetCommunity[] =ob.toString().split(",");
                dt.put("fStreet",fStreetCommunity[0]);
                if(fStreetCommunity.length==2){
                    dt.put("fStreet",fStreetCommunity[1]);
                }
                else  if(fStreetCommunity.length==3){ dt.put("fStreet",fStreetCommunity[1]);
                    dt.put("fCommunity",fStreetCommunity[2]);
                }
            }
            String columnName[] = { "编号", "姓名", "年龄", "性别", "电话", "地址", "街道办", "社区", "日期", "项目", "服务人", "备注" };
            String propertyName[] = { "rownum", "fName", "fAge", "fGender", "fPhone", "fAddress", "fStreet", "fCommunity", "fBegintime", "fServiceType", "fServiceStaff", "fRemarks" };
            ExportModel exportModel = new ExportModel();
            exportModel.setSheetName(list.get(i).getfName());
            exportModel.setTitleName("hello");
            exportModel.setColumnName(columnName);
            exportModel.setPropertyName(propertyName);
            exportModel.setDataList(results);
            exportModels.add(exportModel);
      }
        //生成Excel
        String path = this.filePath(request);
        path +=UUID.randomUUID()+ "服务老人表.xls";
        PoiExcelExport excel = new PoiExcelExport(path);
        excel.wirteExcel(exportModels);
        return path;
    }

    /**
     * 导出老人台账信息
     */
    public String exportElderlyAccountInfo(SelectServiceRecord selectServiceRecord, HttpServletRequest request){
        int month =0; //结束月份
        int index =1; //开始月份
        int count=0;
        String pCode="01";
        List<ExportModel> exportModels = new ArrayList<>();
        List<SysDept> list  =null;
        if(selectServiceRecord.getfQuantumTimeBegin() !=null && !"".equals(selectServiceRecord.getfQuantumTimeBegin())){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String begin=format.format(selectServiceRecord.getfQuantumTimeBegin());
            String end=format.format(selectServiceRecord.getfQuantumTimeEnd());
            index=Integer.parseInt(begin.substring(5,7));
            month=Integer.parseInt(end.substring(5,7));
            if(index>month){
                month=month+12;
            }
        }else{
            Calendar calendar=Calendar.getInstance();
            //获得当前时间的月份，月份从0开始所以结果要加1
            month=calendar.get(Calendar.MONTH)+1;
        }
        if(selectServiceRecord.getfStreetCommunity()!=null && !"".equals(selectServiceRecord.getfStreetCommunity()) ){
            pCode=selectServiceRecord.getfStreetCommunity();
        }
        list  =deptService.sysDeptList(pCode);
        for(int i=0; i< list.size(); i++ ){
           SelectServiceRecord sServiceRecord=new SelectServiceRecord();
            if( selectServiceRecord.getfStreetCommunity()==null || "".equals(selectServiceRecord.getfStreetCommunity())){
                sServiceRecord.setfStreetCommunity(list.get(i).getfId());
            }
            sServiceRecord.setfQuantumTimeBegin(selectServiceRecord.getfQuantumTimeBegin());
            sServiceRecord.setfQuantumTimeEnd(selectServiceRecord.getfQuantumTimeEnd());
            sServiceRecord.setfServiceType(selectServiceRecord.getfServiceType());
            sServiceRecord.setfServiceStaffID(selectServiceRecord.getfServiceStaffID());
            //其中获取的街道社区为一个字段用，分开表示
            List<Map<String, Object>> results = serviceRecordMapper.exportElderlyAccountInfo(sServiceRecord);
            int p=1;
            for(Map<String,Object> rowData : results){
                for (int j=index; j<= month; j++){
                    SelectServiceRecord record =new SelectServiceRecord ();
                    if(selectServiceRecord.getfQuantumTimeBegin() !=null && !"".equals(selectServiceRecord.getfQuantumTimeBegin())){
                        record.setfMonth(Integer.toString(j));
                    }
                    record.setfElderly((String)rowData.get("fName"));
                    record.setfStreetCommunity(list.get(i).getfId());
                    record.setfMonth(Integer.toString(j));
                    SelectServiceRecord listInfo = serviceRecordMapper.exportAnyInfo(record);
                    //将查询的月份依次拼接放入rowData结果中
                    if(listInfo!=null){
                        if(j==index){
                            rowData.put("fBegintime",listInfo.getfBeginTime());
                            rowData.put("fServiceType",listInfo.getfServiceType());
                            rowData.put("fServiceStaff",listInfo.getfServiceStaff());
                        }else {
                            rowData.put( "fBegintime"+p,listInfo.getfBeginTime());
                            rowData.put( "fServiceType"+p,listInfo.getfServiceType());
                            rowData.put("fServiceStaff"+p,listInfo.getfServiceStaff());
                            p++;
                        }
                    }else{
                        if(j==index){
                            rowData.put("fBegintime","");
                            rowData.put("fServiceType","");
                            rowData.put("fServiceStaff","");
                        }else {
                            rowData.put( "fBegintime"+p,"");
                            rowData.put( "fServiceType"+p,"");
                            rowData.put("fServiceStaff"+p,"");
                            p++;
                        }
                    }
                    count=rowData.size();
               }
            }
            //分割街道区域
            for (Map<String, Object> dt:results) {
                Object ob =dt.get("fStreetCommunity");
                if(ob==null){
                    continue;
                }
                String fStreetCommunity[] =ob.toString().split(",");
                dt.put("fStreet",fStreetCommunity[0]);
                if(fStreetCommunity.length==2){
                    dt.put("fStreet",fStreetCommunity[1]);
                }
               else  if(fStreetCommunity.length==3){ dt.put("fStreet",fStreetCommunity[1]);
                  dt.put("fCommunity",fStreetCommunity[2]);
                }
            }
            String sheetName0 = "生活困难老人日常照料服务情况记录单";
            String sheetName1 = "社区总人数应"+results.size()+"人，已补完（不含失能人员）";
            String[] head = new String[]{ "序号", "老人姓名", "年龄", "性别", "联系电话", "家庭住址", "所属街办", "社区", "备注","服务次数 ","未服务次数"}; //在excel中的第3行每列的参数
            int cou=0;
            int unm=0;
            String[] head0=new String[head.length+((month-index)+1)];
            System.arraycopy(head, 0, head0, 0, head.length);
           for (int j=index; j<= month; j++){
               if(j>12){
                head0[head.length+cou]=(j-12)+"月";
               }else{
               head0[head.length+cou]=j+"月";
               }
               cou+=+1;
          }
            String[] head1 = new String[] { "服务日期", "服务项目", "服务人员" };//在excel中的第4行每列（合并列）的参数
            String propertyName0 [] = { "rownum", "fName", "fAge", "fGender", "fPhone", "fAddress", "fStreet", "fCommunity" , "fRemarks","fServicetime","fSurplustime" };
            String propertyName[] = new String[propertyName0.length+((month-index)+1)*3];
            System.arraycopy(propertyName0, 0, propertyName, 0, propertyName0.length);
            int f=1;
            for (int j=index; j<= month; j++){
                if(j==index){
                    propertyName[propertyName0.length+unm]="fBegintime";
                    propertyName[propertyName0.length+(unm+1)]= "fServiceType";
                    propertyName[propertyName0.length+(unm+2)]= "fServiceStaff";
                }else {
                        propertyName[propertyName0.length+unm]="fBegintime"+f;
                        propertyName[propertyName0.length+(unm+1)]= "fServiceType"+f;
                        propertyName[propertyName0.length+(unm+2)]= "fServiceStaff"+f;
                    f++;
                }
                unm+=+3;
            }
            Object columnName[] ={sheetName0,sheetName1,head0,head1} ;
            ExportModel exportModel = new ExportModel();
            exportModel.setSheetName(list.get(i).getfName());
            exportModel.setTitleName("hello");
            exportModel.setColumnNames(columnName);
            exportModel.setPropertyName(propertyName);
            exportModel.setDataList(results);
            exportModel.setCount(count);
            exportModels.add(exportModel);

        }
        //生成Excel
        String path = this.filePath(request);
        path +=UUID.randomUUID()+ "老人台账表.xls";
        PoiExcelExport excel = new PoiExcelExport(path);
        excel.wirteExcels(exportModels);
        return path;
    }
    public String filePath(HttpServletRequest request){
        File cat = new File(request.getSession().getServletContext().getRealPath("/"));
        String uuid = UUIDUtil.getUUID();
        String path = cat.getParent() + "\\measurfile\\";
        File fileDir = new File(path);
        if(!fileDir.exists()) {
            fileDir.mkdirs();
        }
        return path;
    }
}
